package com.imgrate.migration.controller;

import com.imgrate.migration.entity.Server;
import com.imgrate.migration.service.ServerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/servers")
@RequiredArgsConstructor
@Slf4j
@CrossOrigin(origins = "*")
public class ServerController {
    
    private final ServerService serverService;
    
    @PostMapping
    public ResponseEntity<Server> createServer(@RequestBody Server server) {
        try {
            Server createdServer = serverService.createServer(server);
            return ResponseEntity.ok(createdServer);
        } catch (Exception e) {
            log.error("创建服务器失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping
    public ResponseEntity<List<Server>> getAllServers() {
        List<Server> servers = serverService.getAllServers();
        return ResponseEntity.ok(servers);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Server> getServerById(@PathVariable Long id) {
        Optional<Server> server = serverService.getServerById(id);
        if (server.isPresent()) {
            return ResponseEntity.ok(server.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<Server> updateServer(@PathVariable Long id, @RequestBody Server serverDetails) {
        try {
            Server updatedServer = serverService.updateServer(id, serverDetails);
            return ResponseEntity.ok(updatedServer);
        } catch (Exception e) {
            log.error("更新服务器失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteServer(@PathVariable Long id) {
        try {
            serverService.deleteServer(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("删除服务器失败: {}", e.getMessage());
            return ResponseEntity.badRequest().build();
        }
    }
    
    @GetMapping("/os/{osType}")
    public ResponseEntity<List<Server>> getServersByOsType(@PathVariable String osType) {
        List<Server> servers = serverService.getServersByOsType(osType);
        return ResponseEntity.ok(servers);
    }
}